<?php

namespace App\Http\Controllers\Api;

use App\Model\AdminLog;
use App\Model\AudioApi;
use App\Model\ChannelStatistics;
use App\Model\Device;
use App\Model\DiamondConsumeStatistics;
use App\Model\DiamondOutput;
use App\Model\EnterAnItemStatistics;
use App\Model\EnterAnItemStatisticsFields;
use App\Model\FinanceBeforeKkWealth;
use App\Model\FinanceDiamondPayRule;
use App\Model\FinancePearlStream;
use App\Model\FinancePearlWealth;
use App\Model\FinanceWallet;
use App\Model\FinanceWealthStream;
use App\Model\FinanceWealthTotal;
use App\Model\IncomeStatistics;
use App\Model\IncreaseKkValueLogs;
use App\Model\KkBalanceStatistics;
use App\Model\MinusKkValueLogs;
use App\Model\ComputeMonthWater;
use App\Model\ModifyKkValue;
use App\Model\Number;
use App\Model\OperationLogs;
use App\Model\OutAnItemStatistics;
use App\Model\PearlConsumeStatistics;
use App\Model\PearlOutput;
use App\Model\RoomMonthWater;
use App\Model\RoomWealthStream;
use App\Model\Union;
use App\Model\UserRegisterLog;
use App\Model\Users;
use Illuminate\Http\Request;
use App\Model\ThrowingPrizeLog;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use phpDocumentor\Reflection\Types\Object_;

class FinanceController extends BaseController
{
    protected $apiModel;

    public function __construct(Request $request, IncomeStatistics $incomeStatistics)
    {
        parent::__construct($request);
        $this->model = $incomeStatistics;
        $this->apiModel = new AudioApi();
    }

    /**
     * 收入统计
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        return $this->toJson(self::SUCCESS, $this->model->getList($request));
    }

    /**
     * 入账统计
     * @param Request $request
     * @param EnterAnItemStatistics $enterAnItemStatistics
     * @return \Illuminate\Http\JsonResponse
     */
    public function getEnterAnItemStatistics(Request $request, EnterAnItemStatistics $enterAnItemStatistics)
    {
        return $this->toJson(self::SUCCESS, $enterAnItemStatistics->getList($request));
    }

    /**
     * 追加字段
     * @param Request $request
     * @param EnterAnItemStatisticsFields $enterAnItemStatisticsFields
     * @return \Illuminate\Http\JsonResponse
     */
    public function createEnterAnItemStatisticsFields(Request $request, EnterAnItemStatisticsFields $enterAnItemStatisticsFields)
    {
        $validator = Validator::make($request->all(), [
            'desc' => 'bail|required|string',
            'value' => ['bail', 'required', 'string', Rule::notIn('total', 'total_price', 'value', 'created_date', 'filed_id')],
            'type' => ['bail', 'required', Rule::in(0, 1)]
        ], [
            'desc.required' => '描述不可为空',
//            'value.exists' => '值不可重复',
            'value.required' => '值不可为空',
            'value.not_in' => '该字段已被使用'
        ]);
        if ($validator->fails()) {
            return $this->toJson(self::ERROR, [], $validator->errors()->all()[0]);
        }
        if ($request->input('is_new') === 0) {
            $enterAnItemStatisticsFields->createData($request);
        } elseif ($request->input('is_new') === 1) {
            $enterAnItemStatisticsFields->updateData($request);
        }
//        Artisan::call('add_field',[
//            'table' => $request->input('type') == '0' ? 'enter_an_item_statistics' : 'out_an_item_statistics',
//            'field' => $request->input('value'),
//            'comment' => $request->input('desc')
//        ]);
        return $this->toJson(self::SUCCESS);
    }

    /**
     * 删除字段
     * @param $id
     * @param EnterAnItemStatisticsFields $enterAnItemStatisticsFields
     * @return \Illuminate\Http\JsonResponse
     */
    public function deleteField($id, EnterAnItemStatisticsFields $enterAnItemStatisticsFields)
    {
        $enterAnItemStatisticsFields->deleteData($id);
        return $this->toJson(self::SUCCESS);
    }

    /**
     * 获取字段列表
     * @param Request $request
     * @param EnterAnItemStatisticsFields $enterAnItemStatisticsFields
     * @return \Illuminate\Http\JsonResponse
     */
    public function getEnterAnItemStatisticsFields(Request $request, EnterAnItemStatisticsFields $enterAnItemStatisticsFields)
    {
        return $this->toJson(self::SUCCESS, $enterAnItemStatisticsFields->getList($request));
    }

    /**
     * 创建入账记录
     * @param Request $request
     * @param EnterAnItemStatistics $enterAnItemStatistics
     * @return \Illuminate\Http\JsonResponse
     */
    public function createEnterAnItemStatistics(Request $request, EnterAnItemStatistics $enterAnItemStatistics)
    {
        if ($enterAnItemStatistics->createData($request)) {
            OperationLogs::createData($request, OperationLogs::FINANCE, '创建入账记录');
            return $this->toJson();
        }
        return $this->toJson(self::ERROR);
    }

    /**
     * 出账统计
     * @param Request $request
     * @param OutAnItemStatistics $outAnItemStatistics
     * @return \Illuminate\Http\JsonResponse
     */
    public function getOutAnItemStatistics(Request $request, OutAnItemStatistics $outAnItemStatistics)
    {
        return $this->toJson(self::SUCCESS, $outAnItemStatistics->getList($request));
    }

    /**
     * 创建出账记录
     * @param Request $request
     * @param OutAnItemStatistics $outAnItemStatistics
     * @return \Illuminate\Http\JsonResponse
     */
    public function createOutAnItemStatistics(Request $request, OutAnItemStatistics $outAnItemStatistics)
    {
        if ($outAnItemStatistics->createData($request)) {
            OperationLogs::createData($request, OperationLogs::FINANCE, '创建出账记录');
            return $this->toJson();
        }
        return $this->toJson(self::ERROR);
    }

    /**
     * 删除进帐统计
     * @param Request $request
     * @param EnterAnItemStatistics $enterAnItemStatistics
     * @return \Illuminate\Http\JsonResponse
     */
    public function deleteEnterAnItemStatistics(Request $request, EnterAnItemStatistics $enterAnItemStatistics)
    {
        $result = $enterAnItemStatistics->destroyData($request->input('created_date'));
        OperationLogs::createData($request, OperationLogs::FINANCE, '删除进帐统计');
        return $this->toJson(self::SUCCESS, $result);
    }

    /**
     * 删除出账统计
     * @param Request $request
     * @param OutAnItemStatistics $outAnItemStatistics
     * @return \Illuminate\Http\JsonResponse
     */
    public function deleteOutAnItemStatistics(Request $request, OutAnItemStatistics $outAnItemStatistics)
    {
        $result = $outAnItemStatistics->destroyData($request->input('created_date'));
        OperationLogs::createData($request, OperationLogs::FINANCE, '删除出账统计');
        return $this->toJson(self::SUCCESS, $result);
    }

    /**
     * 钻石产出
     * @param Request $request
     * @param DiamondOutput $diamondOutput
     * @return \Illuminate\Http\JsonResponse
     */
    public function getDiamondOutputList(Request $request, DiamondOutput $diamondOutput)
    {
        return $this->toJson(self::SUCCESS, $diamondOutput->getList($request));
    }

    /**
     * 扣除金币列表
     * @param Request $request
     * @param MinusKkValueLogs $minusKkValueLogs
     * @return \Illuminate\Http\JsonResponse
     */
    public function getMinusKkValueList(Request $request, MinusKkValueLogs $minusKkValueLogs)
    {
        return $this->toJson(self::SUCCESS, $minusKkValueLogs->getList($request));
    }

    /**
     * 扣除金币
     * @param Request $request
     * @param MinusKkValueLogs $minusKkValueLogs
     * @return \Illuminate\Http\JsonResponse
     */
    public function createMinusKkValue(Request $request, MinusKkValueLogs $minusKkValueLogs, FinanceWallet $financeWallet)
    {
        $validator = Validator::make($request->all(), [
            'uuid' => 'bail|string|required',
            'user_id' => 'bail|integer|required',
            'kk_value' => 'bail|integer|required'
        ], [
            'uuid.required' => 'UUID必须',
            'user_id.required' => 'USER_ID必须',
            'kk_value.required' => '金币必须'
        ]);
        if ($validator->fails()) {
            return $this->toJson(self::ERROR, [], $validator->errors()->all()[0]);
        }
        $res = curl_request(getKkaudioApiUrl() . '/inner/finance/back/kk/minus', [
            'user_id' => $request->input('user_id'),
            'kk_value' => $request->input('kk_value')
        ], 'json', 'POST');
        if ($res['code'] === 0) {
            $finance_wallet = $financeWallet->getKkBalanceByUserId($request->input('user_id'));
            $user = new Users();
            $user_info = $user->getKkaudioUserTable($request->input('user_id'));
            $request_arr = $request->all();
            $request_arr['nickname'] = $user_info[0]->nickname ?? '错误姓名';
            OperationLogs::createData($request, OperationLogs::FINANCE, '扣除金币', $request->input('uuid'));
            return $this->toJson(self::SUCCESS, $minusKkValueLogs->createData($request_arr, $finance_wallet->kk_balance));
        }
        return $this->toJson(self::ERROR, [], $res['msg']);
    }

    /**
     * 钻石消耗
     * @param Request $request
     * @param DiamondConsumeStatistics $diamondConsumeStatistics
     * @return \Illuminate\Http\JsonResponse
     */
    public function getDiamondConsumeStatisticsList(Request $request, DiamondConsumeStatistics $diamondConsumeStatistics)
    {
        return $this->toJson(self::SUCCESS, $diamondConsumeStatistics->getList($request));
    }

    /**
     * 金币统计
     * @param Request $request
     * @param KkBalanceStatistics $kkBalanceStatistics
     * @return \Illuminate\Http\JsonResponse
     */
    public function getKkBalanceStatisticsList(Request $request, KkBalanceStatistics $kkBalanceStatistics)
    {
        return $this->toJson(self::SUCCESS, $kkBalanceStatistics->getList($request));
    }

    /**
     * 渠道商统计
     * @param Request $request
     * @param ChannelStatistics $channelStatistics
     * @return \Illuminate\Http\JsonResponse
     */
    public function getChannelStatisticsList(Request $request, ChannelStatistics $channelStatistics)
    {
        return $this->toJson(self::SUCCESS, $channelStatistics->getList($request));
    }


    /**
     * 月流水统计
     * @param Request $request
     * @param ChannelStatistics $channelStatistics
     * @return \Illuminate\Http\JsonResponse
     */
    public function getMonthWaterList(Request $request, RoomMonthWater $roomMonthWater)
    {
        return $this->toJson(self::SUCCESS, $roomMonthWater->getRoomMonthSumWater($request));
    }


    /*
     * 生成上月统计数据
     * */
    public function createMonthWater(Request $request, RoomMonthWater $roomMonthWater)
    {
        $data = [];
        $ret = self::SUCCESS;
        do {
            $where['month'] = date('Ym', strtotime('-1 month'));
            $res = $roomMonthWater->checkRoomWaterList($where);
            if ($res) {
                $ret = self::MONTH_WATER_STATISTICS;
                break;
            }
        } while (false);
        return $this->toJson($ret, $data);
    }

    //查看房间流水
    public function showMonthWater(Request $request, RoomMonthWater $roomMonthWater)
    {
        return $this->toJson(self::SUCCESS, $roomMonthWater->getAllRoomWaterList($request));
    }

    //修改记录
    public function editKkWaterLog(Request $request, ModifyKkValue $modifyKkValue)
    {
        $list = $modifyKkValue->getList($request);
        return $this->toJson(self::SUCCESS, $list);
    }

    //修改金币
    public function addKkWaterLog(Request $request, ModifyKkValue $modifyKkValue)
    {
        $res = $modifyKkValue->createLog($request, $this->user);
        if ($res)
            return $this->toJson(self::SUCCESS);
        return $this->toJson(self::ERROR);
    }

    //结算金币
    public function updateKkBalance(Request $request)
    {
        //修改接口
        $data['month'] = $request->input('month') ?? date('Ym', strtotime('-1 month'));
        $res = curl_request(getKkaudioApiUrl() . '/inner/finance/room/wealth_month/update_kk_balance', $data, 'urlencoded', 'GET');
        if ($res['code'] !== 0) {
            return $this->toJson(self::ERROR, $res, $res['msg']);
        }
        return $this->toJson(self::SUCCESS);
    }


    /**
     * 珍珠产出
     * @param Request $request
     * @param DiamondOutput $diamondOutput
     * @return \Illuminate\Http\JsonResponse
     */
    public function getPearlOutputList(Request $request, PearlOutput $pearlOutput)
    {
        return $this->toJson(self::SUCCESS, $pearlOutput->getList($request));
    }

    /**
     * 珍珠消耗
     * @param Request $request
     * @param DiamondOutput $diamondOutput
     * @return \Illuminate\Http\JsonResponse
     */
    public function getPearlConsumeStatisticsList(Request $request, PearlConsumeStatistics $pearlConsumeStatistics)
    {
        return $this->toJson(self::SUCCESS, $pearlConsumeStatistics->getList($request));
    }


    public function cbdRoomWealthStream(Request $request, RoomWealthStream $roomWealthStream)
    {
        return $this->toJson(self::SUCCESS, $roomWealthStream->getAllCabinWealthWater($request));
    }


    //小屋流水统计
    public function cabinWealthStream(Request $request, FinancePearlStream $financePearlWealth)
    {
        return $this->toJson(self::SUCCESS, $financePearlWealth->getAllCabinWealthWater($request));
    }


    /**
     * 发放金币列表
     * @param Request $request
     * @param MinusKkValueLogs $minusKkValueLogs
     * @return \Illuminate\Http\JsonResponse
     */
    public function getIncreaseKkValueList(Request $request, IncreaseKkValueLogs $increaseKkValueLogs)
    {
        $datas = $increaseKkValueLogs->getList($request);
        return $this->toJson(self::SUCCESS, $datas);
    }

    /**
     * 发放金币
     * @param Request $request
     * @param IncreaseKkValueLogs $increaseKkValueLogs
     * @return \Illuminate\Http\JsonResponse
     */
    public function createIncreaseKkValue(Request $request, IncreaseKkValueLogs $increaseKkValueLogs, FinanceWallet $financeWallet)
    {
        $validator = Validator::make($request->all(), [
            'uuid' => 'bail|string|required',
            'user_id' => 'bail|integer|required',
            'kk_value' => 'bail|integer|required'
        ], [
            'uuid.required' => 'UUID必须',
            'user_id.required' => 'USER_ID必须',
            'kk_value.required' => '金币必须'
        ]);
        if ($validator->fails()) {
            return $this->toJson(self::ERROR, [], $validator->errors()->all()[0]);
        }
        $this->apiModel->sendMsgApi($request->input('user_id'), $request->input('msg'));
        $res = curl_request(getKkaudioApiUrl() . '/inner/finance/back/kk/minus', [
            'user_id' => $request->input('user_id'),
            'kk_value' => $request->input('kk_value')
        ], 'json', 'POST');
        if ($res['code'] === 0) {
            $finance_wallet = $financeWallet->getKkBalanceByUserId($request->input('user_id'));
            $user = new Users();
            $user_info = $user->getKkaudioUserTable($request->input('user_id'));
            $request_arr = $request->all();
            $request_arr['nickname'] = $user_info[0]->nickname ?? '错误姓名';
            OperationLogs::createData($request, OperationLogs::FINANCE, '新增金币');
            return $this->toJson(self::SUCCESS, $increaseKkValueLogs->createData($request_arr, $finance_wallet->kk_balance));
        }


        return $this->toJson(self::ERROR);
    }


    public function getPayRuleList(Request $request)
    {
        $list = FinanceDiamondPayRule::whereIn('plat_type', [1, 2])->orderBy('plat_type')->get();
        return $this->toJson(self::SUCCESS, ['data' => $list, 'total' => count($list)]);
    }


    public function updatePayRule(Request $request)
    {
        $postData = $request->input();
        if ($postData['rule_id'] == 0) {
            $model = new FinanceDiamondPayRule();
        } else {
            $model = FinanceDiamondPayRule::find($postData['rule_id']);
        }
        $model->price = $postData['price'];
        $model->plat_type = $postData['plat_type'];
        $model->diamond_amount = $postData['diamond_amount'];
//        $model->diamond_desc = $postData['diamond_desc'];
        $model->save();
        return $this->toJson(self::SUCCESS);
    }

    public function delPayRule(Request $request)
    {
        $postData = $request->input();
        if (!($postData['rule_id'] > 0)) {
            return $this->toJson(self::ERROR, [], '参数错误');
        }
        FinanceDiamondPayRule::find($postData['rule_id'])->delete();
        return $this->toJson(self::SUCCESS);
    }

    //预支记录列表
    public function beforeKkList(Request $request, FinanceBeforeKkWealth $financeBeforeKkWealth)
    {
        return $this->toJson(self::SUCCESS, $financeBeforeKkWealth->getBeforeList($request->input()));
    }

    //预支记录列表
    public function getBeforeDayList(Request $request, FinanceBeforeKkWealth $financeBeforeKkWealth)
    {
        $data = $request->input();
        $data['end_date'] = date('Y-m-d', time() - 86400);
        $res = $financeBeforeKkWealth->getList($data);
        if (!$res['data']) {
            $res = curl_request(getKkaudioApiUrl() . '/inner/finance/room/wealth_before/create_before_kk_wealth', $data, 'urlencoded', 'GET');
            if ($res['code'] === 0) {
                OperationLogs::createData($request, OperationLogs::FINANCE, '流水结算预支统计', $data['room_uid']);
                $res = $financeBeforeKkWealth->getList($data);
            }
        }
        return $this->toJson(self::SUCCESS, $res);
    }

    public function updateBeforeKkWealth(Request $request, FinanceBeforeKkWealth $financeBeforeKkWealth)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'bail|required',
            'room_id' => 'bail|required',
            'total' => 'bail|required',
            'surplus_total' => 'bail|required',
            'content' => 'bail|required',
        ], [
            'id.required' => '参数错误',
            'room_id.required' => '房间id必须',
            'total.required' => '修改金额必须',
            'surplus_total.required' => '今日预支金额必须',
            'content.required' => '预支说明必须',
        ]);
        if ($validator->fails()) {
            return $this->toJson(self::ERROR, [], $validator->errors()->all()[0]);
        }
        $data = $request->input();
        if ($data['surplus_total'] < $data['total']) return $this->toJson(self::ERROR, [], '修改金额错误');
        $apiData['id'] = $data['id'];
        $apiData['total'] = $data['total'] * 100; //元->分
        $res = curl_request(getKkaudioApiUrl() . '/inner/finance/room/wealth_before/update_before_kk_wealth', $apiData, 'json', 'POST');
        if ($res['code'] !== 0) {
            OperationLogs::createData($request, OperationLogs::FINANCE, '流水结算扶持币统计', $data['id']);
            return $this->toJson(self::ERROR, [], '生成修改记录失败');
        }
        //生成修改记录
        $token = $request->header('x-token') ?? '';
        $users = Users::findByToken($token);
        $insertData['admin_id'] = $users->id;
        $insertData['admin_name'] = $users->name;
        $insertData['before_id'] = $data['id'];
        $insertData['surplus_total'] = $data['surplus_total'] * 100; //元-》分
        $insertData['room_id'] = $data['room_id'];
        $insertData['total'] = $data['total'] * 100;//元-》分
        $insertData['content'] = $data['content'];
        $insertData['day'] = $data['day'];
        $res = $financeBeforeKkWealth->createBeforeLog($insertData);
        if (!$res) {
            return $this->toJson(self::ERROR, [], '生成修改记录失败');
        }
        return $this->toJson(self::SUCCESS, $res);
    }

    public function updateKkWealthForBeforeTable(Request $request)
    {
        $apiData['room_id'] = $request->input('room_id') ?? 1;
        $res = curl_request(getKkaudioApiUrl() . '/inner/finance/room/wealth_before/update_kk_wealth_for_before_table', $apiData, 'json', 'POST');
        if ($res['code'] === 0) {
            OperationLogs::createData($request, OperationLogs::FINANCE, '流水结算扶持币统计', $apiData['room_id']);
            return $this->toJson(self::SUCCESS, $res);
        }
        // print_r(xxx);
        return $this->toJson(self::ERROR, [], '预支失败');
    }

    //修改记录
    public function getBeforeKkLog(Request $request, FinanceBeforeKkWealth $financeBeforeKkWealth)
    {
        return $this->toJson(self::SUCCESS, $financeBeforeKkWealth->getLogList($request->input()));
    }

    public function getDeviceList(Request $request, Device $device)
    {
        $admin = $this->user;
        $channel_arr = [];
        $start_date = date('Y-m-d');
        $type = [];
        $timestamp = [];
        if ($admin['id'] == 43) { //后台用户  可查阅渠道号  和开始统计时间
            $channel_arr = [9003];
            $start_date = '2020-04-08'; //开始计算时间
            $timestamp = [strtotime($start_date), time()];
            $type = ['iPhone'];// iPhone Android
        }
        if (empty($channel_arr)) {
            return $this->toJson(self::ERROR, [], '当前权限无法查询该统计');
        }
        $limit = $request->input('limit', 10);
        $idfa = $request->input('idfa', '');
        $dateTime = $request->input('dateTime');
        if (!empty($dateTime)) {
            $s_time = strtotime($dateTime[0]);
            $e_time = strtotime($dateTime[1]);
            if ($s_time < strtotime($start_date)) {
                $s_time = strtotime($start_date);
            }
            if ($e_time < strtotime($start_date)) {
                $e_time = time();
            }
            $timestamp = [$s_time, $e_time];
        }
        $data = $device->getList($channel_arr, $type, $timestamp, $idfa, $limit);

        return $this->toJson(self::SUCCESS, $data);
    }


    /**
     * 获取公会资质认证金记录
     * @param Request $request
     * @param Union $union
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUnionDepositList(Request $request, Union $union)
    {
        $startTime = $request->input('begin_date');
        $endTime = $request->input('end_date');

        if (strtotime($startTime) > strtotime($endTime)) {
            return $this->toJson(self::ERROR, [], '查询时间范围有误');
        }
        $result = $union->getUnionDepositList($request);

        return $this->toJson(self::SUCCESS, $result);
    }


    /**
     * 撤回退还公会资质认证金
     * @param Request $request
     * @param Union $union
     * @return \Illuminate\Http\JsonResponse
     */
    public function recallPayment(Request $request, Union $union)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'required',
            'union_id' => 'required'
        ], [
            'id.required' => '列表ID不能为空',
            'union_id.required' => '公会ID不可为空'
        ]);
        if ($validator->fails()) {
            return $this->toJson(self::PARAM_ERROR, [], $validator->errors()->all()[0]);
        }

        // 获取当前登录用户ID
        $admin = $this->user;

        $data = [
            'union_id' => $request->input('union_id'),
            'log_id' => $request->input('id'),
            'opt_id' => $admin['id']
        ];

        $res = $union->recallPayment($data);
        if ($res['code']) {
            return $this->toJson(self::ERROR, [], $res['msg']);
        }

        return $this->toJson(self::SUCCESS);
    }

}
